﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Data;
using System.Drawing;
using System.Text;
using System.Windows.Forms;
using UI.ParentForm;
using UI.Lib;
using Components;
using Com.Seezt.Skins;
using System.Collections;
using UI.Lib.Factory;
using Controls;

namespace UI.Invoice
{
    public partial class FrmTic3a00Medit : BaseSedit
    {
        private string comcode = string.Empty;
        ToolStripButton btnSearch = null; //查询
        ToolStripButton btnTakeTickit = null; //开票按钮
        ToolStripButton btnRefresh = null;

        public FrmTic3a00Medit(string modulecode, string action)
            : base(modulecode, action)
        {
            InitializeComponent();

            this.SaveCallFuntion = "Tic3a00Manager$SaveData"; //保存的方法
            IsAfterSaveCloseWin = false;

            this.tbMain.Enabled = false;
        }

        protected override void PageInit()
        {
            this.tbSummary.DefaultWidth = 160;
        }

        protected override bool BeforeCreateChildControl()
        {
            this.tbMain.DefaultWidth = 160;
            return true;
        }

        protected override void AddToolButton()
        {
            btnRefresh = base.CreateToolBtn("R", "  重置  ", new EventHandler(delegate
            {
                if (MsgBox.Show(this, "提示", "确定重置吗？", MessageBoxButtons.YesNo) == DialogResult.Yes)
                {
                    Reset();
                }
            }));

            btnRefresh.ToolTipText = "F5";
            this.tspTop.Items.Insert(0, btnRefresh); //添加查询按钮

            //加入查询、开票按钮
            btnTakeTickit = base.CreateToolBtn("W", "  开票  ", new EventHandler(delegate
            {
                DoTakeTickit();
            }));

            btnTakeTickit.ToolTipText = "F9";
            this.tspTop.Items.Insert(0, btnTakeTickit); //添加开票按钮

            btnSearch = base.CreateToolBtn("S", "  查询  ", new EventHandler(delegate
            {
                DoSearch();
            }));

            btnSearch.ToolTipText = "Home";
            this.tspTop.Items.Insert(0, btnSearch); //添加查询按钮

            this.tspSave.Visible = true;
        }

        private void Reset()
        {
            this.tbMain.Enabled = false;
            this.tbSummary.Enabled = true;
            this.dgvDtl.ReadOnly = false;
            this.tbSummary.Clear();
            this.tbMain.Clear();
            this.dgvDtl.DataSource = null;
            this.comcode = string.Empty;

            this.tbSummary.FocusFirst();
        }

        protected override void FormKeyDown(KeyEventArgs e)
        {
            if (e.KeyCode == Keys.Home) //增加快捷键
            {
                if (base.CanClickButton(btnSearch)) btnSearch.PerformClick();
            }
            else if (e.KeyCode == Keys.F9)
            {
                if (base.CanClickButton(btnTakeTickit)) btnTakeTickit.PerformClick();
            }
            else if (e.KeyCode == Keys.F5)
            {
                if (base.CanClickButton(btnRefresh)) btnRefresh.PerformClick();
            }
        }

        public override bool BeforePopWin(string name, ref string where, ref string[] others)
        {
            if ("s_sellercode" == name) //销售商
            {
                where = string.Format(" status ='1' {0} ", Context.GetAppKeyWhere("usercode", true));
            }
            else if ("s_shopcode" == name || "addcode" == name || "comcode" == name) //门店
            {
                string sellerid = Validation.ToString(this.tbSummary.GetValue("s_sellerid"));
                if (string.IsNullOrEmpty(sellerid))
                {
                    MsgBox.Show(this, "请先选择销售商！");
                    this.tbSummary.Focus("s_sellercode");
                    return false;
                }

                if ("s_shopcode" == name)
                {
                    where = string.Format("slistid = '{0}' {1} ", sellerid, Context.GetAppKeyWhere("muser", true));
                }
                else if ("addcode" == name)
                {
                    where = string.Format("status = '01' AND slistid = '{0}' ", sellerid);
                }

                else if ("comcode" == name) //公司代码
                {
                    where = string.Format("slistid = '{0}' ", sellerid);
                }
            }

            return true;
        }

        //查询
        private void DoSearch()
        {
            string errmsg = this.tbSummary.CheckSelf();
            if (!string.IsNullOrEmpty(errmsg))
            {
                MsgBox.ShowErrorMsg(this, errmsg);
                return;
            }

            //组织查询条件
            Hashtable where = new Hashtable();
            where["sellerid"] = Validation.ToString(this.tbSummary.GetValue("s_sellerid"));
            where["shopid"] = Validation.ToString(this.tbSummary.GetValue("shopid"));
            where["status"] = Validation.ToString(this.tbSummary.GetValue("s_status"));
            where["muser"] = Context.Comocde;
            where["comcode"] = Validation.ToString(this.tbSummary.GetValue("comcode"));

            object start = this.tbSummary.GetValue("s_startdate"); //开始时间
            where["startdate"] = null == start ? Global.MinDate : Convert.ToDateTime(start);

            object end = this.tbSummary.GetValue("s_endate"); //结束时间
            where["endate"] = null == end ? Global.MaxDate : Convert.ToDateTime(end);

            DataTable data = CommonHelper.Entity.ExecFun("ord3a00query", where);
            where = null;

            if (DataTableHelper.Entity.IsEmptyTable(data))
            {
                this.dgvDtl.DataSource = null;
                MsgBox.Show(this, "未能查询到任何订单数据，请调整查询条件！");
                return;
            }

            this.dgvDtl.DataSource = data;
            this.dgvDtl.Focus();

            //设置状态在状态为“已收货”订单前面有多选框，可以按“空格”键进行选择，其它状态的订单不能选择；
            //ResetCtlStatus();
        }

        void ResetCtlStatus()
        {
            string status = string.Empty;
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                status = Validation.ToString(dr.Cells["status"].Value);

                if ("10" != status && "5" != status) //已回单和已发货
                {
                    dr.Cells["choose"].ReadOnly = true;
                }
            }
        }

        protected override void AfterCreateControlInSummary(string colName, Control c)
        {
            if (colName == "agiopct")
            {
                PsTextBox txt = c as PsTextBox;
                txt.ValueChanged += new TextBoxX.DgValueChanged(txt_ValueChanged);
            }
        }

        void txt_ValueChanged(object sender, EventArgs e)
        {
            SetAgioamt(); //开票折扣率改变时，自动计算折扣额等数据
        }

        //开票
        private void DoTakeTickit()
        {
            this.dgvDtl.EndEdit();

            bool hasChooseItem = false;
            bool checkState = false;
            double accamt = 0; //收货总额
            double agiopct = 0;//折扣额
            foreach (DataGridViewRow dr in this.dgvDtl.Rows)
            {
                checkState = Validation.ToBool(dr.Cells["choose"].EditedFormattedValue);
                if (checkState == false) continue;

                accamt += Validation.ToDouble(dr.Cells["accamt"].Value);
                agiopct += Validation.ToDouble(dr.Cells["agiopct"].Value); //折扣率

                if (!string.IsNullOrEmpty(comcode) && comcode != Validation.ToString(dr.Cells["comcode"].Value))
                {
                    MsgBox.ShowErrorMsg(this, "必须选择同一公司的订单才能开票！");
                    return;
                }

                if (string.IsNullOrEmpty(comcode))
                {
                    comcode = Validation.ToString(dr.Cells["comcode"].Value);
                }

                hasChooseItem = true;
            }

            if (hasChooseItem == false) //为选择有效的订单
            {
                MsgBox.ShowErrorMsg(this, "请选择订单！");
                return;
            }

            //设置汇总信息
            this.tbMain.SetValue("sellercode", this.tbSummary.GetValue("s_sellercode"));
            this.tbMain.SetValue("sellername", this.tbSummary.GetValue("s_sellername"));
            this.tbMain.SetValue("ordamt", accamt); //总的收货额
            this.tbMain.SetValue("ordagioamt", Validation.ToDouble(accamt * agiopct, 3)); //折扣额为收货额*订单折扣；

            //得到付款日期和付款费用
            DataTable refDt = CommonHelper.Entity.ExecFun("getpaydate",
               new KeyValuePair<string, object>("sellid", Validation.ToString(this.tbSummary.GetValue("s_sellerid"))),
               new KeyValuePair<string, object>("comcode", comcode));

            if (!DataTableHelper.Entity.IsEmptyTable(refDt))
            {
                this.tbMain.SetValue("planpaydate", Validation.ToDate(refDt.Rows[0]["paydate"]));
                this.tbMain.SetValue("agiopct", Validation.ToDouble(refDt.Rows[0]["spct"]));  //发票折扣率
            }

            this.tbMain.SetValue("muser", Context.User.Empname);
            this.tbMain.Focus("agiopct");

            this.tbMain.Enabled = true;
            this.tbSummary.Enabled = false;
            this.dgvDtl.ReadOnly = true;
        }

        //计算发票折扣额
        private void SetAgioamt()
        {
            double ordamt = Validation.ToDouble(tbMain.GetValue("ordamt")); //总的收获额
            double ordagioamt = Validation.ToDouble(tbMain.GetValue("ordagioamt"));  //折扣额为收货额
            double agiopct = Validation.ToDouble(tbMain.GetValue("agiopct")); //发票折扣率
            double agioamt = Validation.ToDouble((ordamt - ordagioamt) * agiopct, 3);
            this.tbMain.SetValue("agioamt", agioamt);

            //设置开票总额
            this.tbMain.SetValue("ticamt", ordamt - ordagioamt - agioamt);
        }

        protected override void AutoSize()
        {
            this.dgvDtl.AutoSizeColumnsMode = DataGridViewAutoSizeColumnsMode.AllCells;
        }

        protected override Hashtable SaveOtherData()
        {
            Hashtable tb = tbMain.GetAllValue();
            tb["comcode"] = comcode;
            tb["sellerid"] = Validation.ToString(this.tbSummary.GetValue("s_sellerid"));

            return tb;
        }

        protected override void AfterSaveData(bool isSuccess)
        {
            if (isSuccess)
            {
                Reset();
            }
        }

        protected override bool Check()
        {
            if (this.tbMain.Enabled == false)
            {
                MsgBox.ShowErrorMsg(this, "未选择开票订单，不需要保存！");
                return false;
            }

            string errmsg = tbMain.CheckSelf();
            if (!string.IsNullOrEmpty(errmsg))
            {
                MsgBox.ShowErrorMsg(this, errmsg);
                return false;
            }

            return true;
        }

        /// <summary>
        /// 重写明细数据保存
        /// </summary>
        protected override DataTable SetDtlSaveData()
        {
            int rowCount = this.dgvDtl.Rows.Count;
            if (!allowDtlEmpty && 0 == rowCount)
            {
                MessageBox.Show("明细数据为空，不能保存！", "提示");
                return null;
            }

            this.dgvDtl.EndEdit();
            DataTable dt = new DataTable();
            dt.TableName = "DTLDATA";
            DataColumn dc;

            dc = new DataColumn();
            dc.ColumnName = "listid";
            dt.Columns.Add(dc);
            bool checkState = false;
            for (int j = 0; j < dgvDtl.Rows.Count; j++)
            {
                checkState = Validation.ToBool(this.dgvDtl.Rows[j].Cells["choose"].EditedFormattedValue);
                if (checkState == false) continue;

                DataRow dr = dt.NewRow();

                dr["listid"] = Validation.ToString(this.dgvDtl.Rows[j].Cells["listid"].Value);

                AfterRowExData(dr);//行提取值后调用
                dt.Rows.Add(dr);
            }

            return dt;
        }
    }
}
